package com.xcc.myzxing;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PointF;
import android.util.AttributeSet;
import android.view.View;

public class PointsOverlayView extends View {
    private PointF[] points;
    private Paint paint;
    private boolean isRuning;
    private int w, h, nowH;
    private ChangeThread thread;

    public PointsOverlayView(Context context) {
        super(context);
        init();
    }

    public PointsOverlayView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public PointsOverlayView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init() {
        paint = new Paint();
        paint.setColor(Color.YELLOW);
        paint.setStyle(Paint.Style.FILL);
        paint.setStrokeWidth(5);
        isRuning = true;
        //thread = new ChangeThread();
        //thread.start();
    }

    public void setPoints(PointF[] points) {
        this.points = points;
        invalidate();
    }

    public void draw(Canvas canvas) {
        super.draw(canvas);
        if (points != null) {
            for (PointF pointF : points) {
                canvas.drawCircle(pointF.x, pointF.y, 10, paint);
            }
        }
        w = getWidth();
        h = getHeight();
        if (nowH > 0) {
            canvas.drawLine(0, nowH, w, nowH, paint);
        }
    }

    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        isRuning = false;
    }

    public class ChangeThread extends Thread {
        private final static int max = 1000;
        private final static int sleep = 10;
        private final static int step = 1;

        public void run() {
            int idx = 0;
            while (isRuning) {
                //System.out.println("线程在运行");
                try {
                    sleep(sleep);
                } catch (InterruptedException e) {
                }
                if (w > 0 && h > 0) {
                    idx += step;
                    if (idx > max)
                        idx = 0;
                    nowH = h * idx / max;
                    if (isRuning) postInvalidate();
                }
            }
        }
    }
}
